import { observable, action, toJS } from 'mobx';
import { WeaForm, WeaTableNew } from 'comsMobx';
import { message } from 'antd';
import { WeaLocaleProvider } from 'ecCom';
import * as Api from '../../apis/setting/mailSign';
import { ValidateForm } from './util';

const { TableStore } = WeaTableNew;
const { getLabel } = WeaLocaleProvider;
const initalState = {
  editTitle: '',
  editFields: [],
  editRichValue: '',
  signType: 0,
  electOptions: [],
  electAllOptions: [],
  electOtherOptions: [],
  electDefaultImg: {},
  electInfo: {},
  qrCode: '',
  electEdit: false,
  electSelected: [],
  editType: '',
  editId: '',
  electEditKey: '',
  innStorage: {},
  editIsSuccess: false,
  editLoading: false,
};
export default class SignStore {
  @observable signTable = new TableStore();
  @observable editForm = new WeaForm();
  @observable editTitle = initalState.editTitle; // 编辑--Dialog-Title
  @observable editFields = initalState.editFields;
  @observable editRichValue = initalState.editRichValue; // 编辑--富文本值
  @observable signType = initalState.signType; // 编辑--签名类型
  @observable electOptions = initalState.electOptions; // 电子签名默认选项
  @observable electAllOptions = initalState.electAllOptions; // 电子签名全部选项
  @observable electOtherOptions = initalState.electOtherOptions; // 电子签名剩余选项
  @observable electDefaultImg = initalState.electDefaultImg; // 电子签名默认选项
  @observable electInfo = initalState.electInfo; // 电子签名回显值
  @observable qrCode = initalState.qrCode; // 电子签名二维码
  @observable electSelected = initalState.electSelected;
  @observable editType = initalState.editType;
  @observable editId = initalState.editId;
  @observable electEditKey = initalState.electEditKey; // 电子签名编辑时key值存储
  @observable innStorage = initalState.innStorage; // 电子签名编辑时数据存储
  @observable editIsSuccess = initalState.editIsSuccess; // 电子签名校验是否通过
  @observable editLoading = initalState.editLoading; // Condition加载Loading

  @action setStoreState = (params) => {
    Object.keys(params).forEach((key) => {
      this[key] = params[key];
    });
  }

  @action clear = () => this.setStoreState(initalState);

  @action getMailSign = (initPage = false) => {
    Api.getMailSign().then((res) => {
      initPage ? this.signTable.getDatas(res.sessionkey) :
      this.signTable.getDatas(res.sessionkey, 1);
    });
  }

  @action operateUserMailSign = async (params) => {
    let res = await Api.operateUserMailSign(params);
    return res;
  }

  @action getEmailSignCondition = (params, callback) => {
    this.editLoading = true;
    Api.getEmailSignCondition(params).then((res) => {
      const { allOptions, conditioninfo, data, electronSignEntity } = res;
      this.editForm.initFormFields(conditioninfo);
      this.editFields = conditioninfo;
      this.signType = this.editForm.getFormParams().signType * 1;
      this.electDefaultImg = data || {};
      this.electInfo = electronSignEntity;
      this.electAllOptions = allOptions.map((v) => {
        let newOption = { ...v };
        newOption.isEdit = false;
        newOption.selected = true;
        if (newOption.key !== 'jobname' && newOption.key !== 'url') {
          this.electOptions.push(newOption);
          this.electSelected.push(newOption.id);
        } else {
          this.electOtherOptions.push({ ...newOption, isEdit: true });
        }
        return newOption;
      });
      this.editLoading = false;
      if (callback) callback();
    });
  }

  @action addElectItem = () => {
    if (toJS(this.electOptions).length >= toJS(this.electAllOptions).length) {
      message.error(getLabel(384459, '不能再添加了！！'));
    } else {
      this.electEditKey = toJS(this.electOtherOptions)[0] ? toJS(this.electOtherOptions)[0].key : '';
      this.electOptions = [...toJS(this.electOptions).map(option => ({ ...option, isEdit: false })), this.electOtherOptions.shift()];
      this.electSelected = toJS(this.electOptions).map(v => `${v.id}`);
    }
  }

  @action deleteElectItem = (value) => {
    this.electOptions = this.electOptions.filter(v => v.key !== value.key);
    this.electSelected = toJS(this.electOptions).map(v => `${v.id}`);
    this.electOtherOptions.push({ ...value, isEdit: true });
  }

  @action getMailSignEntity = (params, callback) => {
    Api.getMailSignEntity(params).then((res) => {
      const { data, electronSignEntity, emailSignEntity } = res;
      const signType = emailSignEntity.signType; // 签名类型
      for (let attr in emailSignEntity) {
        if (attr !== 'id' && attr !== 'signContent' && attr !== 'userId') {
          this.editForm.updateFields({ [attr]: { value: `${emailSignEntity[attr]}` } });
        }
      }
      this.editRichValue = emailSignEntity.signContent;
      this.signType = emailSignEntity.signType;
      this.electOptions = [];
      this.electOtherOptions = [];
      if (signType) { // 电子签名
        this.electDefaultImg = data;
        this.qrCode = `data:image/png;base64,${electronSignEntity.qrcodepath}`;
        this.electSelected = electronSignEntity.selected.split(',');
        toJS(this.electAllOptions).map((item) => {
          if (electronSignEntity.selected.split(',').indexOf(`${item.id}`) === -1) {
            this.electOtherOptions.push({ ...item, isEdit: true });
          }
        });
        electronSignEntity.selected !== '' && electronSignEntity.selected.split(',').map((item) => {
          let option = toJS(this.electAllOptions).filter(v => v.id * 1 === item * 1)[0];
          this.electOptions.push({ ...option, isEdit: false });
        });
        this.electInfo = electronSignEntity;
      }
      if (callback) callback();
    });
  }

  @action createQRcode = () => {
    let newParams = this.electInfo;
    for (let key in newParams) {
      if (key === 'id' || key === 'signId' || key === 'qrcodepath') {
        delete newParams[key];
      }
    }
    let params = { ...newParams, selected: toJS(this.electSelected).join() };
    Api.createQRcode(params).then((res) => {
      this.qrCode = `data:image/png;base64,${res.QRcodeMap}`;
    });
  }

  @action electInfoChange = (key, value) => {
    this.electInfo[key] = value;
  }

  // select change
  @action electSelectChange = (key, olddata) => {
    if (key !== olddata.key) {
      this.electEditKey = key;
      this.electOptions = toJS(this.electOptions).map((option) => {
        if (option.key === olddata.key) {
          return toJS(this.electOtherOptions).filter(v => v.key === key)[0];
        } return option;
      });
      this.electOtherOptions = [...toJS(this.electOtherOptions).filter(v => v.key !== key), olddata];
    }
  }

  @action electInfoOnBlur = (value, key, reg) => {
    if (reg.reg && Array.isArray(reg.reg) && value !== '') {
      let tempArr = reg.reg.filter(v => v.test(value));
      if (tempArr.length == 0) {
        message.error(getLabel('513190', '请输入正确格式的信息！'));
        this.electInfo[key] = toJS(this.innStorage[key]);
        this.editIsSuccess = true;
        return;
      }
    }
    this.electOptions = toJS(this.electOptions).map((v) => {
      if (v.key === key) {
        return { ...v, isEdit: false };
      }
      return v;
    });
  }

  @action onEditSubmit = (callback) => {
    if (this.editIsSuccess) {
      this.editIsSuccess = false;
      return;
    }
    ValidateForm(this.editForm, callback);
  }
}
